/*
 * Built by Ganymede
 * Copyright (c) 2022 Ganymede
 */

import { createConnection } from "typeorm";
import { checkConfig, config } from "./config"
import { Contract } from "./contract";
import { Logger } from "./components/logger";
import { WorkerManager } from "./components/worker";
import { Server } from "./components/server";

checkConfig();
export const logger = new Logger();

let shutdown = false;

async function main() {
  // logger.info("[PXTokenCollector] Made with ❤ by Ganymede");
  // logger.info("[PXTokenCollector] Copyright (c) 2022 Ganymede All Rights Reserved.");

  const contract = new Contract();
  await contract.init();

  // const database = await createConnection(config.database);
  // await database.synchronize();

  const workerManager = new WorkerManager(contract);
  workerManager.start();

  const server = new Server(workerManager);
  server.start().catch(e => logger.error(e));

  while (!shutdown) {
    await sleep(3000);
  }

  workerManager.stop();
  server.stop();
}

export function sleep(ms: number) {
  return new Promise(r => setTimeout(r, ms));
}

main().catch(async err => {
  await logger.error(err);
  process.exit();
});

process.once("SIGINT", () => {
  logger.info("[Main] SIGINT received. Shutting down.");
  shutdown = true;
});
